<template>
  <!-- 推广卡片 -->
  <div>
    <div class="batch-form-model" id="promotion_card" style="padding:20px 0; border:1px solid #C2C2C3;">
      <a-form-model
        ref="ruleForms"
        :model="cardForm"
        :rules="rules"
        label_align='right'
        layout="horizontal"
        :label-col="{ span: 3 }"
        :wrapper-col="{ span: 20 }"
      >
        <a-form-model-item >
          <span slot="label" >
            <a-icon type="exclamation-circle" :title="'您可上传产品图/logo/宣传图等，建议图片突出卖点'"/>
            卡片主图
          </span>
          <a-upload
            name="avatar"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            action="#"
            :before-upload="beforeUpload"
            :customRequest="customRequest"
          >
            <div class="upload-info" @mouseleave="r => id_image_mask = false" @mouseenter="r => id_image_mask = true">
              <img v-if="imageInfo.url" style="width:108px;height:108px;" :src="imageInfo.url" alt="avatar" />
              <div v-else>
                <a-button type="primary" @click.stop="r => is_selectMaterial = true ">图片库</a-button>
                <a-icon :type="loading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">
                  上传图片
                </div>
              </div>
              <div v-if="imageInfo.url && id_image_mask" class="upload-mask">
                <span class="upload-mask-btn" @click.stop="r =>is_selectMaterial = true ">更换图片</span>
              </div>
            </div>
          </a-upload>
        </a-form-model-item>

        <a-form-model-item>
          <span slot="label" >
            <a-icon type="exclamation-circle" :title="'建议填写您推广产品的名称。如XX（您的品牌）牛奶、XX游戏；XX（抖音昵称）直播等'"/>
            卡片标题
          </span>
          <a-form-model-item prop="product_description">
            <a-input style="width:50%" :maxLength="7" v-model="cardForm.product_description"></a-input>
            <span style="margin-left:10px">{{ cardForm.product_description.length + ' / 7' }}</span>
          </a-form-model-item>
        </a-form-model-item>

        <a-form-model-item>
          <span slot="label" >
            <a-icon type="exclamation-circle" :title="'在抖音信息流显示。建议填写：最能体现您推广产品特点的内容。如遮瑕防水、鲜香不腥等'"/>
            推广卖点
          </span>
  
          <div class="double-form-vertical">
            <div>
              <div>
                <a-button type="primary" icon="plus" style="margin-right:10px;" @click="addSellingPoints">添加卖点</a-button>
                <span>{{ cardForm.product_selling_points.length }}</span> / <span>{{ limit_selling_points_number }}</span>
              </div>
              <a-form-model-item ref="product_selling_points">
                <div v-for="(item,index) in cardForm.product_selling_points" :key="index">
                  <a-input
                    :maxLength="9"
                    placeholder="推广卖点在 6 ~ 9 个字之间(必填)"
                    v-model="cardForm.product_selling_points[index]"
                    :style="{'width':'50%' , 'color': prompt(cardForm.product_selling_points[index]) }"
                  >
                  </a-input>
                  <span style="margin: 0 10px">{{ cardForm.product_selling_points[index].length + ' / 9' }}</span>
                  <a-icon v-if="cardForm.product_selling_points.length > 1" type="delete" style="cursor: pointer;" @click="deleteSellingPoints(index)" />
                </div>
              </a-form-model-item>

            </div>
          </div>
        </a-form-model-item>

        <a-form-model-item label="行动号召">

          <div class="double-form-vertical">
            <a-radio-group
              v-model="cardForm.enable_personal_action"
              button-style="solid"
            >
              <a-radio-button :value="true"> 开启智能优选 </a-radio-button>
              <a-radio-button :value="false"> 关闭智能优选 </a-radio-button>
            </a-radio-group>
            <span style="color:#C9C9CA;" v-if="cardForm.enable_personal_action" >系统将基于字节领先的技术能力和实时的投放数据，在每次抖音广告显示时，挑选最有利于转化的文案进行显示，帮助您提升转化能力。</span>

            <a-select v-model="cardForm.call_to_action" style="width:50%;">
              <a-select-option
                v-for="(item,index) in call_to_actions"
                :key="index"
                :value="item"
              >
                {{ item }}
              </a-select-option>
            </a-select>
            <span style="color:#C9C9CA;" >在无法使用智能优选的流量场景下，将使用上方文案展示给用户。</span>
          </div>

        </a-form-model-item>

      </a-form-model>
    </div>

    <material-item-select
      v-if="is_selectMaterial"
      :selectMaterialratio='selectMaterialratio'
      :materialType="materialType"
      :vhType="vhType"
      @closeModal="r => is_selectMaterial = false "
      @confirmAddMaterial="r => imageInfo = r[0] "
    ></material-item-select>
  </div>
</template>

<script>
import { getCardRecommendTitle } from "@/api/headlinesApi";
import { imageUpload } from "@/api/adv/upload";

export default {
  props:{
    value:{
      type:Object,
      require:true,
      default:()=>{
        return {
          product_image_id:'', // 卡片主图 id
          product_description:'', // 卡片标题
          enable_store_pack:false, // 门店 
          enable_personal_action:true,  //智能优选
          call_to_action:'阅读全文', // 行动号召
          product_selling_points:['商家倾情推荐']   //商品卖点
        }
      }
    }
  },
  components:{
    materialItemSelect:() => import('./materialItemSelect')
  },
  data(){
    return {
      accountIds:'',
      imageInfo:{},
      loading: false,
      id_image_mask:false,
      limit_selling_points_number:10,   // 卖点限制个数
      // 库
      is_selectMaterial:false,
      selectMaterialratio:'PROMOTION_CARD',
      materialType:'image',
      vhType:'horizontal',
      cardForm:this.value,
      call_to_actions:this.$store.state.batchCreated.call_to_action,
      // call_to_actions:['查看详情','下一章','去阅读','阅读全文'],
      rules:{
        product_description: [{ required: true,message:'请填写卡片标题', trigger: 'change' }],
        product_image_id: [{ required: true,message:'请填写卡片标题', trigger: 'change' }],
      }
    }
  },
  computed:{
    prompt(){
      return function(item) {
        return item.length < 6 ? 'red' : ''
      }
    }
  },
  watch:{
    'imageInfo':function (params) {
      this.cardForm.product_image_id = params.id  // 卡片主图更新 更新id
    },
    '$store.state.batchCreated.campaign':function (campaign) {
      localStorage.setItem('account_id',campaign.account_id[0].account_id)  // 上传卡片
      this.accountIds = campaign.account_id
      this.getRecommendTitle()
    },
  },
  methods:{
    async customRequest(data){
      let account_id = localStorage.getItem('account_id')
      const formData = new FormData()
      formData.append('file', data.file)
      formData.append('account_id', account_id)

      const res = await imageUpload(formData)
      if( res.data.width === 108 && res.data.height === 108 ) this.imageInfo = res.data
      else this.imageInfo = {},this.$Tip('请上传 108 * 108 尺寸图')
      setTimeout( () => { this.loading = false }, 1000 );
    },
    // 判断图片大小
    async isSize (file, width, height)  {
      return await new Promise((resolve, reject) => {
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = () => {
          let valid = img.width === width && img.height === height;
          valid ? resolve(true) : this.$Tip('图片尺寸为 108 * 108 ，请修改后重新上传！'),setTimeout(() => { this.loading = false },1000); reject(false);
        };
        img.src = _URL.createObjectURL(file);
      });
    },
    async beforeUpload(file) {
      this.loading = true
      const is_size = await this.isSize(file, 108, 108) // 判断图片大小
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!');
      }
      return isJpgOrPng && isLt2M && is_size;
    },
    // 获取推广号召文案
    getRecommendTitle(){
      let account_id = this.accountIds[0].account_id
      let quest = {
        advertiser_id:account_id,
        text_type:'CALL_TO_ACTION'
      }
      getCardRecommendTitle(account_id,quest).then((res)=>{
        this.$store.commit('SET_CALL_TO_ACTION',res.data.list)
        
        this.call_to_actions = this.$store.state.batchCreated.call_to_action
        this.cardForm.call_to_action = this.$store.state.batchCreated.call_to_action[0]
      })
    },
    // 添加卖点
    addSellingPoints(){
      if( this.cardForm.product_selling_points.length < this.limit_selling_points_number ){
        this.cardForm.product_selling_points.push(`商家倾情推荐${this.cardForm.product_selling_points.length+1}`)
      }
    },
    // 删除卖点
    deleteSellingPoints(index){
      this.cardForm.product_selling_points.splice(index,1)
    },
    // 验证信息规则
    async rulesInfo(){
      let is_ = true
      this.$refs['ruleForms'].validate(valid => {
        if( Object.values(this.cardForm).some(v=>v==='') ) return ( alert('请完善卡片'),document.getElementById("promotion_card").scrollIntoView() , is_ = false , false )
        for (const item of this.cardForm.product_selling_points) {
          if( item.length < 6 ) return alert('推广卖点必需大于6个字')
        }
        if (valid) {
          // 判断属性值是否为空
          // this.$emit('input',this.cardForm)
        } else {
          is_ = false
        }
      });
      return is_;
    }
  }
}
</script>

<style lang="less" scoped>
  .ant-upload-picture-card-wrapper{
    width: 80%;
  }
  .upload-info{
    position: relative;
  }

  .avatar-uploader > .ant-upload {
    width: 148px;
    height: 148px;
  }
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
  .upload-mask{
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.4);
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    .upload-mask-btn{
      position: absolute;
      width: 70%;
      height: 25px;
      background-color:#1990FF;
      border-radius: 5px;
      color: blanchedalmond;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%);
    }
  }
  

</style>